<template>
  <div class="change-record-container">
    <el-card class="change-record-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><RefreshLeft /></el-icon>
            项目变更记录
            <el-tag v-if="props.projectData.project_name" type="primary" size="small" style="margin-left: 10px;">
              {{ props.projectData.project_name }}
            </el-tag>
          </h2>
          <p class="description">
            记录并管理所有项目变更项，包含审批流程
            <span v-if="props.projectData.project_id" style="color: #e6a23c; font-weight: 500;">
              (项目编号: {{ props.projectData.project_id }})
            </span>
          </p>
        </div>
        <div class="header-actions">
          <el-button v-if="canAdd" type="primary" @click="openDialog()" class="create-btn">
            <el-icon><Plus /></el-icon>
            提交变更
          </el-button>
          <el-button type="primary" @click="refreshData" class="refresh-btn" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>

      <!-- 项目选择 -->
      <div class="project-selector" v-if="!props.projectData.project_id">
        <el-select v-model="selectedProject" placeholder="选择项目" style="width: 300px" @change="handleProjectChange">
          <el-option label="全部项目" value="all" />
          <el-option 
            v-for="project in projectList" 
            :key="project.project_id" 
            :label="project.project_name" 
            :value="project.project_id" 
          />
        </el-select>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索变更内容、发起方、文件名..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterInitiator" placeholder="发起方" clearable>
          <el-option 
            v-for="initiator in initiatorOptions" 
            :key="initiator" 
            :label="initiator" 
            :value="initiator" 
          />
        </el-select>
        <el-date-picker
          v-model="filterDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          clearable
        />
      </div>

      <!-- 变更记录表格 -->
      <el-table
        :data="paginatedChangeList"
        stripe
        border
        class="change-table"
        v-loading="loading"
        empty-text="暂无变更记录"
      >
        <el-table-column prop="change_file_code" label="变更文件编号" min-width="150" />
        <el-table-column prop="project_id" label="所属项目" width="120" />
        <el-table-column prop="change_date" label="变更日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.change_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="change_content" label="变更内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="initiator" label="发起方" width="120" />
        <el-table-column prop="reason" label="变更原因" min-width="150" show-overflow-tooltip />
        <el-table-column prop="reported_amount" label="上报金额" width="120">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.reported_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="final_audit_amount" label="审计金额" width="120">
          <template #default="scope">
            {{ scope.row.final_audit_amount ? `¥${formatAmount(scope.row.final_audit_amount)}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="external_approval" label="外部批准" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.external_approval) }}
          </template>
        </el-table-column>
        <el-table-column prop="internal_approval" label="内部批准" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.internal_approval) }}
          </template>
        </el-table-column>
        <el-table-column label="附件文件" width="150">
          <template #default="scope">
            <div v-if="scope.row.filename && scope.row.fileurl">
              <div class="file-info">
                <span class="filename" :title="scope.row.filename">{{ scope.row.filename }}</span>
                <el-button 
                  size="small" 
                  type="success" 
                  @click="downloadFile(scope.row.fileurl, scope.row.filename)"
                  class="download-btn"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
              </div>
            </div>
            <span v-else class="no-file">无附件</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetail(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button v-if="hasPermission" size="small" type="warning" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button v-if="hasPermission" size="small" type="danger" @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-section" v-if="filteredChangeList.length > 0">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredChangeList.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 变更统计 -->
      <div class="change-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ changeStats.total }}</div>
                <div class="stat-label">总变更数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ changeStats.totalAmount }}</div>
                <div class="stat-label">总上报金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ changeStats.auditAmount }}</div>
                <div class="stat-label">总审计金额</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ changeStats.thisMonth }}</div>
                <div class="stat-label">本月变更</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 变更创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑变更' : '提交变更'"
      width="800px"
      align-center
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属项目" prop="project_id">
              <el-select v-model="form.project_id" placeholder="请选择项目" style="width: 100%" :disabled="!!props.projectData.project_id || !hasPermission">
                <el-option 
                  v-for="project in projectList" 
                  :key="project.project_id" 
                  :label="project.project_name" 
                  :value="project.project_id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变更文件编号" prop="change_file_code">
              <el-input v-model="form.change_file_code" placeholder="请输入变更文件编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="变更日期" prop="change_date">
              <el-date-picker
                v-model="form.change_date"
                type="date"
                placeholder="选择变更日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发起方" prop="initiator">
              <el-input v-model="form.initiator" placeholder="请输入发起方" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="变更内容" prop="change_content">
          <el-input v-model="form.change_content" type="textarea" :rows="3" placeholder="请输入变更内容摘要" />
        </el-form-item>
        <el-form-item label="变更原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" :rows="3" placeholder="请输入变更原因" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上报金额" prop="reported_amount">
              <el-input-number 
                v-model="form.reported_amount" 
                :precision="2" 
                :step="0.01" 
                :min="0"
                style="width: 100%"
                placeholder="请输入上报金额"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审计金额" prop="final_audit_amount">
              <el-input-number 
                v-model="form.final_audit_amount" 
                :precision="2" 
                :step="0.01" 
                :min="0"
                style="width: 100%"
                placeholder="请输入审计金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="外部批准日期" prop="external_approval">
              <el-date-picker
                v-model="form.external_approval"
                type="date"
                placeholder="选择外部批准日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内部批准日期" prop="internal_approval">
              <el-date-picker
                v-model="form.internal_approval"
                type="date"
                placeholder="选择内部批准日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeFileUpload"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar"
            class="file-upload"
          >
            <template #trigger>
              <el-button type="primary" size="small">
                <el-icon><Plus /></el-icon>
                选择文件
              </el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word、Excel、文本、压缩包等格式，文件大小不超过50MB
              </div>
            </template>
          </el-upload>
          
          <!-- 显示已有文件信息 -->
          <div v-if="form.filename && form.fileurl" class="existing-file">
            <div class="file-card">
              <div class="file-header">
                <el-icon class="file-type-icon"><Document /></el-icon>
                <div class="file-info">
                  <span class="filename">{{ form.filename }}</span>
                  <span class="file-status">已上传</span>
                </div>
              </div>
              <div class="file-actions">
                <el-button 
                  size="small" 
                  type="success" 
                  @click="downloadFile(form.fileurl, form.filename)"
                  class="action-btn download-btn"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="removeExistingFile"
                  class="action-btn remove-btn"
                >
                  <el-icon><Delete /></el-icon>
                  移除
                </el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="hasPermission" type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>

    <!-- 变更详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="变更详情"
      width="800px"
      align-center
    >
      <div class="change-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="变更文件编号">{{ selectedChange.change_file_code }}</el-descriptions-item>
          <el-descriptions-item label="所属项目">{{ selectedChange.project_id }}</el-descriptions-item>
          <el-descriptions-item label="变更日期">{{ formatDate(selectedChange.change_date) }}</el-descriptions-item>
          <el-descriptions-item label="发起方">{{ selectedChange.initiator }}</el-descriptions-item>
          <el-descriptions-item label="上报金额">¥{{ formatAmount(selectedChange.reported_amount) }}</el-descriptions-item>
          <el-descriptions-item label="审计金额">{{ selectedChange.final_audit_amount ? `¥${formatAmount(selectedChange.final_audit_amount)}` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="外部批准日期">{{ formatDate(selectedChange.external_approval) }}</el-descriptions-item>
          <el-descriptions-item label="内部批准日期">{{ formatDate(selectedChange.internal_approval) }}</el-descriptions-item>
          <el-descriptions-item label="变更内容" :span="2">
            {{ selectedChange.change_content || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="变更原因" :span="2">
            {{ selectedChange.reason || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedChange.remark || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="附件文件" :span="2" v-if="selectedChange.filename && selectedChange.fileurl">
            <div class="file-detail">
              <div class="file-info-display">
                <span class="filename">{{ selectedChange.filename }}</span>
                <el-button 
                  size="small" 
                  type="success" 
                  @click="downloadFile(selectedChange.fileurl, selectedChange.filename)"
                  class="download-btn"
                >
                  <el-icon><Download /></el-icon>
                  下载文件
                </el-button>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { RefreshLeft, Plus, Search, View, Edit, Delete, Refresh, Download, Document } from '@element-plus/icons-vue'
import { 
  getProjectChangeList, 
  getProjectChangeListByProjectId,
  createProjectChange, 
  updateProjectChange, 
  deleteProjectChange 
} from '../../api/projectChange'
import { getProjectList } from '../../api/project'
import { uploadSingleFile, getFileUrl } from '../../api/fileUpload'
import apiConfig from '../../utils/apiConfig'

// 定义props
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  projectData: {
    type: Object,
    default: () => ({})
  }
})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 检查是否为当前项目的项目经理
const isProjectManager = computed(() => {
  if (!props.projectData || !props.projectData.project_manager) {
    return false
  }
  // 检查当前用户是否为该项目的项目经理
  return currentUser.value.username === props.projectData.project_manager || 
         currentUser.value.userId === props.projectData.project_manager ||
         currentUser.value.id === props.projectData.project_manager
})

// 检查是否有权限操作（只有当前项目的项目经理可以操作）
const hasPermission = computed(() => {
  return isProjectManager.value
})

// 检查是否可以新增和删除（只有当前项目的项目经理可以操作）
const canAdd = computed(() => {
  return isProjectManager.value
})

// 响应式数据
const selectedProject = ref('all')
const changeList = ref([])
const projectList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const searchKeyword = ref('')
const filterInitiator = ref('')
const filterDateRange = ref([])
const formRef = ref()
const selectedChange = ref({})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const form = ref({
  id: null,
  project_id: '',
  change_file_code: '',
  change_date: '',
  change_content: '',
  initiator: '',
  reason: '',
  reported_amount: 0,
  final_audit_amount: 0,
  external_approval: '',
  internal_approval: '',
  remark: '',
  file: null, // 新增文件上传字段
  filename: '',
  fileurl: ''
})

// 表单验证规则
const formRules = {
  project_id: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
  change_file_code: [{ required: true, message: '请输入变更文件编号', trigger: 'blur' }],
  change_date: [{ required: true, message: '请选择变更日期', trigger: 'change' }],
  initiator: [{ required: true, message: '请输入发起方', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }],
  reported_amount: [{ required: true, message: '请输入上报金额', trigger: 'blur' }],
  external_approval: [{ required: true, message: '请选择外部批准日期', trigger: 'change' }],
  internal_approval: [{ required: true, message: '请选择内部批准日期', trigger: 'change' }]
}

// 发起方选项
const initiatorOptions = computed(() => {
  const options = new Set()
  changeList.value.forEach(change => {
    if (change.initiator) {
      options.add(change.initiator)
    }
  })
  return Array.from(options)
})

// 过滤后的变更列表
const filteredChangeList = computed(() => {
  let filtered = changeList.value
  
  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item => 
      item.change_content?.toLowerCase().includes(keyword) ||
      item.initiator?.toLowerCase().includes(keyword) ||
      item.change_file_code?.toLowerCase().includes(keyword) ||
      item.reason?.toLowerCase().includes(keyword) ||
      item.filename?.toLowerCase().includes(keyword)
    )
  }
  
  // 根据发起方过滤
  if (filterInitiator.value) {
    filtered = filtered.filter(item => item.initiator === filterInitiator.value)
  }
  
  // 根据日期范围过滤
  if (filterDateRange.value && filterDateRange.value.length === 2) {
    const [startDate, endDate] = filterDateRange.value
    filtered = filtered.filter(item => {
      const changeDate = item.change_date
      return changeDate >= startDate && changeDate <= endDate
    })
  }
  
  return filtered
})

// 分页后的变更列表
const paginatedChangeList = computed(() => {
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredChangeList.value.slice(start, end)
})

// 变更统计数据
const changeStats = computed(() => {
  const total = filteredChangeList.value.length
  const totalAmount = filteredChangeList.value.reduce((sum, item) => sum + (item.reported_amount || 0), 0)
  const auditAmount = filteredChangeList.value.reduce((sum, item) => sum + (item.final_audit_amount || 0), 0)
  
  const currentMonth = new Date().getMonth()
  const currentYear = new Date().getFullYear()
  const thisMonth = filteredChangeList.value.filter(item => {
    const changeDate = new Date(item.change_date)
    return changeDate.getMonth() === currentMonth && changeDate.getFullYear() === currentYear
  }).length
  
  return { 
    total, 
    totalAmount: formatAmount(totalAmount), 
    auditAmount: formatAmount(auditAmount), 
    thisMonth 
  }
})

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 格式化金额
function formatAmount(amount) {
  if (!amount) return '0.00'
  return parseFloat(amount).toFixed(2)
}

// 下载文件
async function downloadFile(fileUrl, fileName) {
  try {
    console.log('开始下载文件:', fileName, 'URL:', fileUrl)
    
    // 从fileUrl中提取文件类型和文件名
    // fileUrl格式: /uploads/application/filename.ext
    const urlParts = fileUrl.split('/')
    const fileType = urlParts[urlParts.length - 2] // 获取文件类型目录
    const filename = urlParts[urlParts.length - 1] // 获取文件名
    
    console.log('解析的文件信息:', { fileType, filename })
    
    // 使用新的下载API
    const baseURL = apiConfig.getBaseURLSync()
    const downloadUrl = `${baseURL}/api/upload/download/${filename}?type=${fileType}`
    
    console.log('下载URL:', downloadUrl)
    
    // 创建一个隐藏的a标签来下载文件
    const link = document.createElement('a')
    link.href = downloadUrl
    link.setAttribute('download', fileName)
    link.setAttribute('target', '_blank')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('文件下载已开始')
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('文件下载失败')
  }
}

// 移除已有文件
function removeExistingFile() {
  form.value.file = null
  form.value.filename = ''
  form.value.fileurl = ''
  ElMessage.success('已移除附件文件')
}

// 获取项目列表
async function loadProjectList() {
  try {
    const response = await getProjectList({ page: 1, pageSize: 1000 })
    if (response.data && response.data.data) {
      projectList.value = response.data.data
    } else if (Array.isArray(response.data)) {
      projectList.value = response.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  }
}

// 加载项目变更列表
async function loadProjectChange() {
  loading.value = true
  try {
    const currentProjectId = props.projectData.project_id || props.projectId || selectedProject.value
    
    if (currentProjectId && currentProjectId !== 'all') {
      console.log('加载项目变更，项目ID:', currentProjectId)
      
      const res = await getProjectChangeListByProjectId(currentProjectId)
      const allChanges = Array.isArray(res) ? res : []
      
      // 过滤当前项目的数据
      changeList.value = allChanges.filter(item => item.project_id === currentProjectId)
      console.log('当前项目变更数量:', changeList.value.length)
      console.log('变更数据:', changeList.value)
    } else {
      // 加载所有变更
      const response = await getProjectChangeList({ page: 1, pageSize: 1000 })
      if (response.data && response.data.data) {
        changeList.value = response.data.data
      } else if (Array.isArray(response.data)) {
        changeList.value = response.data
      } else {
        changeList.value = []
      }
    }
  } catch (error) {
    ElMessage.error('加载项目变更失败')
    console.error('加载项目变更失败:', error)
    changeList.value = []
  } finally {
    loading.value = false
  }
}

// 项目选择变化
function handleProjectChange() {
  loadProjectChange()
}

// 刷新数据
function refreshData() {
  loadProjectChange()
}

// 打开对话框
function openDialog(change = null) {
  if (change) {
    form.value = { ...change }
    // 如果有文件信息，设置到文件上传组件
    if (change.filename && change.fileurl) {
      // 这里可以设置文件上传组件的显示状态
      // 由于el-upload不支持直接设置文件，我们通过其他方式显示
    }
  } else {
    form.value = {
      id: null,
      project_id: props.projectData.project_id || props.projectId || (selectedProject.value === 'all' ? '' : selectedProject.value),
      change_file_code: '',
      change_date: '',
      change_content: '',
      initiator: '',
      reason: '',
      reported_amount: 0,
      final_audit_amount: 0,
      external_approval: '',
      internal_approval: '',
      remark: '',
      file: null,
      filename: '',
      fileurl: ''
    }
  }
  
  // 重置文件上传组件
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  
  dialogVisible.value = true
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
          // 如果有文件，先上传文件
      let fileInfo = {}
      if (form.value.file) {
        try {
          console.log('开始上传文件:', form.value.file)
          console.log('文件类型:', typeof form.value.file)
          console.log('文件大小:', form.value.file.size)
          console.log('文件名称:', form.value.file.name)
          
          const uploadResponse = await uploadSingleFile(form.value.file)
          console.log('上传响应:', uploadResponse)
          
          if (uploadResponse.data && uploadResponse.data.url) {
            fileInfo = {
              filename: form.value.file.name,
              fileurl: uploadResponse.data.url
            }
            ElMessage.success('文件上传成功')
          } else {
            throw new Error('文件上传失败')
          }
        } catch (error) {
          console.error('文件上传失败:', error)
          console.error('错误详情:', {
            name: error.name,
            message: error.message,
            stack: error.stack,
            response: error.response
          })
          ElMessage.error(`文件上传失败: ${error.message}`)
          return
        }
      }
    
    // 准备提交的数据
    const submitData = { ...form.value }
    if (Object.keys(fileInfo).length > 0) {
      submitData.filename = fileInfo.filename
      submitData.fileurl = fileInfo.fileurl
    }
    
    if (form.value.id) {
      // 更新
      await updateProjectChange(form.value.id, submitData)
      ElMessage.success('变更更新成功')
    } else {
      // 创建
      await createProjectChange(submitData)
      ElMessage.success('变更创建成功')
    }
    
    dialogVisible.value = false
    loadProjectChange()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

// 查看详情
function viewDetail(change) {
  selectedChange.value = change
  detailVisible.value = true
}

// 删除变更
async function handleDelete(id) {
  try {
    await ElMessageBox.confirm('确定要删除这个变更记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteProjectChange(id)
    ElMessage.success('删除成功')
    loadProjectChange()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 分页处理
function handleSizeChange(newSize) {
  pagination.value.pageSize = newSize
  pagination.value.page = 1
}

function handleCurrentChange(newPage) {
  pagination.value.page = newPage
}

// 文件上传相关
const uploadRef = ref()

async function beforeFileUpload(rawFile) {
  const isLt50M = rawFile.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }
  return true
}

async function handleFileChange(file) {
  console.log('文件变更事件:', file)
  console.log('原始文件对象:', file.raw)
  
  // 确保文件对象正确
  if (file.raw && file.raw instanceof File) {
    form.value.file = file.raw
    console.log('文件已设置到表单:', form.value.file)
  } else {
    console.error('无效的文件对象:', file.raw)
    ElMessage.error('文件选择失败，请重试')
  }
}

async function handleFileRemove() {
  form.value.file = null
}

// 监听项目数据变化
watch(() => props.projectData, (newProjectData) => {
  if (newProjectData && newProjectData.project_id) {
    if (dialogVisible.value && !form.value.project_id) {
      form.value.project_id = newProjectData.project_id
    }
    loadProjectChange()
  }
}, { deep: true })

// 监听项目ID变化
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    console.log('项目ID变化，重新加载项目变更:', newProjectId)
    loadProjectChange()
  }
})

// 页面初始化
onMounted(async () => {
  try {
    await loadProjectList()
    await loadProjectChange()
  } catch (error) {
    console.error('项目变更页面初始化失败:', error)
  }
})
</script>

<style scoped>
.change-record-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.change-record-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #e6a23c;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn, .refresh-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.project-selector {
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.change-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-section {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}

.change-stats {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.change-detail {
  padding: 20px 0;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filename {
  font-size: 12px;
  color: #606266;
  word-break: break-all;
  margin-bottom: 4px;
}

.download-btn {
  width: 100%;
}

.no-file {
  color: #909399;
  font-size: 12px;
}

.existing-file {
  margin-top: 12px;
}

.file-info-display {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.file-info-display .filename {
  flex: 1;
  font-size: 14px;
  color: #303133;
  margin-bottom: 0;
}

.file-upload {
  width: 100%;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}

/* 文件上传相关样式 */
.file-upload {
  width: 100%;
}

.existing-file {
  margin-top: 12px;
}

.file-card {
  margin-top: 16px;
  padding: 20px;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.file-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.file-type-icon {
  font-size: 24px;
  color: #409eff;
  padding: 8px;
  background: #f0f9ff;
  border-radius: 8px;
}

.file-info {
  flex: 1;
}

.filename {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.file-status {
  display: inline-block;
  padding: 4px 8px;
  background: #f0f9ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.file-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  border-radius: 8px;
  font-weight: 500;
}

.download-btn {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
}

.download-btn:hover {
  background: linear-gradient(135deg, #5daf34 0%, #7bc95a 100%);
  transform: translateY(-1px);
}

.remove-btn {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  border: none;
}

.remove-btn:hover {
  background: linear-gradient(135deg, #e64242 0%, #f56c6c 100%);
  transform: translateY(-1px);
}

/* 详情页面文件显示样式 */
.file-detail {
  padding: 8px 0;
}

.file-info-display {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-info-display .filename {
  flex: 1;
  font-size: 14px;
  color: #303133;
  margin-bottom: 0;
}

.file-info-display .download-btn {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border: none;
  border-radius: 6px;
  font-weight: 500;
}

.file-info-display .download-btn:hover {
  background: linear-gradient(135deg, #5daf34 0%, #7bc95a 100%);
  transform: translateY(-1px);
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}
</style> 